﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;

namespace QuickAndDirtyXSLT
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            InitEditors();
        }

        private void InitEditors()
        {
            sciXml.ConfigurationManager.Language = "xml";
            sciXsl.ConfigurationManager.Language = "xml";
            sciXml.Margins[0].Width = 20;
            sciXsl.Margins[0].Width = 20;
            sciXml.Indentation.SmartIndentType = ScintillaNET.SmartIndent.Simple;
            sciXsl.Indentation.SmartIndentType = ScintillaNET.SmartIndent.Simple;

        }

        private string Transform(string xsl, string xml)
        {
            var tstream = new MemoryStream();
            var transform = new XslCompiledTransform();
            var writer = XmlTextWriter.Create(tstream, new XmlWriterSettings { ConformanceLevel = ConformanceLevel.Auto });
            var reader = new XmlTextReader(new MemoryStream(Encoding.UTF8.GetBytes(xsl)));


            try
            {
                transform.Load(reader);
            }
            catch (XsltException ex)
            {
                MessageBox.Show(ex.Message);
                return string.Empty;
            }
            finally 
            { 
                reader.Close(); 
            }
            reader = new XmlTextReader(new MemoryStream(Encoding.UTF8.GetBytes(xml)));
            try
            {
                transform.Transform(new XPathDocument(reader), writer);
            }
            catch (InvalidOperationException ex)
            {
                MessageBox.Show(ex.Message);
                return string.Empty;
            }
            finally
            {
                reader.Close();
            }
            writer.Flush();
            tstream.Position = 0;

            var streamReader = new StreamReader(tstream);
            var outXml = streamReader.ReadToEnd();
            streamReader.Close();
            return outXml;

        }

        private void button1_Click(object sender, EventArgs e)
        {
            var txml = Transform(sciXsl.Text, sciXml.Text);
            if (!string.IsNullOrEmpty(txml))
            {
                var frm = new Form2();
                frm.sciXml.Text = txml;
                frm.Show();
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Environment.Exit(0);
        }
    }
}
